/**
 * 扩展类，部分依赖Jquery,BootStrap,EasyUI
 */
var xhExtra = {
    /**
     * 提示信息框
     * --EasyUI.messager
     *
     * @param _options
     *
     * create by 20170318
     */
    showMessage: function(_options) {
        var _default = {
            title: '提示',
            content: '提示内容',
            type: 'info'
        };
        _options = $.extend({}, _default, _options);
        $.messager.alert(_options.title, _options.content, _options.type);
    },
    /**
     * 弹出确认框，确认后执行回调
     * --EasyUI.messager
     *
     * @param _options
     * @param _callback
     * @param _callJson
     *
     * create by ck 20170318
     */
    showConfirm: function(_options, _callback, _callJson) {
        var _default = {
            title: '确认',
            content: '是否确认？'
        };
        _options = $.extend({}, _default, _options);
        $.messager.confirm(_options.title, _options.content, function(_r){
            if(_r && _callback) {
                _callback.call(this, _callJson);
            }
        });
    },
    /**
     * 返回到列表
     *
     * @param _datagrid     --列表对象，有则刷新列表
     *
     * create by ck 20170623
     */
    backToList: function(_datagrid) {
        $('#xh_form').hide();
        $('.xh-datagrid').parent().fadeIn();
        $('body').css('overflow-y', 'hidden');
        if(_datagrid) _datagrid.reload();
    },
    /**
     * 前进到表单
     *
     * @param _edit     --是否编辑，否则重置表单
     *
     * create by ck 20170623
     */
    forwardToForm: function(_edit) {
        $('.xh-datagrid').parent().hide();
        $('#xh_form').fadeIn();
        $('body').css('overflow-y', 'auto');
        if(!_edit){
            $('#bt_form_edit').hide();
            $('#bt_form_reset, #bt_form_add').show();
        }
        else{
            $('#bt_form_add, #bt_form_reset').hide();
            $('#bt_form_edit').show();
        }
        //$('#bt_form_reset').click();
    },
    /**
     * 检查是否有error界面，有则提示错误
     *
     * @param _response
     *
     * create by ck 20170623
     */
    checkError: function(_response) {
        if(_response === '' || typeof _response === 'string'){
            window.top.xhTop.showMessage({
                title: '请求失败！',
                text: _response,
                type: 'error'
            });
            return true;
        }
        if(_response.error){
            window.top.xhTop.showMessage({
                title: _response.error,
                text:  typeof _response.msg === 'string' ? _response.msg : null,
                type: 'error'
            });
            return true;
        }
        return false;
    },
    hasError: function (_response) {
        return (_response === '' || typeof _response === 'string' || _response.error);
    },
    /**
     * 启用按钮
     *
     * @param _dom
     * @param _type
     *
     * create by ck 20170626
     */
    enableButton: function(_dom, _type){
        if(_type === 'eu') {
            _dom.linkbutton('enable');
        }
        else if(_type === 'bs') {
            _dom.removeClass('disabled');
        }
    },
    /**
     * 禁用按钮
     *
     * @param _dom
     * @param _type
     *
     * create by ck 20170626
     */
    disableButton: function(_dom, _type){
        if(_type === 'eu') {
            _dom.linkbutton('disable');
        }
        else if(_type === 'bs') {
            _dom.addClass('disabled');
        }
    },
    /**
     * 检查按钮是否禁用
     *
     * @param _dom
     * @returns {*}
     *
     * create by ck 20170626
     */
    buttonDisabled: function(_dom){
        return _dom.linkbutton('options').disabled;
    },
    /**
     * 询问并传递参数到后台处理
     *
     * @param _url
     * @param _params
     * @param _datagrid
     * @param _text
     * @param _callback
     *
     * create by ck 20170627
     */
    askChangeStatus: function(_url, _params, _datagrid, _text, _callback){
        window.top.swal({
            title: _text || '确认删除？',
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            allowOutsideClick: true,
            showCloseButton: true,
            showLoaderOnConfirm: true,
            type: 'warning',
            preConfirm: function() {
                return new Promise(function (resolve, reject) {
                    xhExtra.ajaxRequest(_url, _params, {table: _datagrid, success: true}, _callback);
                })
            }
        }).then(function(isConfirm) {}, function(dismiss) {});
    },
    /**
     * 传递参数到后台处理
     *
     * @param _url
     * @param _params
     * @param _datagrid
     * @param _callback
     *
     * create by ck 20170627
     */
    // changeStatus: function(_url, _params, _datagrid, _callback){
    //     $.ajax({
    //         url: baseUrl + _url,
    //         type: 'POST',
    //         data: (typeof _params === 'string' || _params instanceof Array) ? {ids: _params} : _params,
    //         dataType: 'json',
    //         complete: function(XMLHttpRequest){
    //             let result = XMLHttpRequest.responseJSON;
    //             if(xhExtra.checkError(result)) return false;
    //             if(result.msg) window.top.xhTop.showMessage({type: 'success', title: result.msg});
    //             if(_datagrid) _datagrid.reload();
    //             if(_callback) _callback.call(this, result);
    //         }
    //     });
    // },
    /**
     * 异步请求
     *
     * @param _url
     * @param _params
     * @param _options
     * @param _callback
     *
     * create by ck 20170627
     */
    ajaxRequest: function(_url, _params, _options, _callback){
        _options = _options || {};
        $.ajax({
            url: baseUrl + _url,
            type: 'POST',
            async: _options.async !== undefined ? _options.async : true,
            data: (typeof _params === 'string' || _params instanceof Array) ? {ids: _params} : (_params || {}),
            dataType: 'json',
            timeout: _options.timeout ? _options.timeout * 1000 : 0,
            complete: function(XMLHttpRequest){
                var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                if(_options.check !== false && xhExtra.checkError(result)) return false;
                if(_options.success && result.msg) window.top.xhTop.showSuccess(result.msg);
                if(_options.table) _options.table.reload();
                if(_callback) _callback.call(this, result);
            }
        });
    },
    /**
     * 绑定基本事件
     *
     * @param _dataGrid
     * @param _form
     * @param _btSave
     * @param _option
     *
     * create by ck 20170701
     */
    bindDefaultFun: function(_dataGrid, _form, _btSave, _option){
        //列表加载后清除已选择信息
        xhExtra.clearLoadSuccess(_dataGrid);
        //重置
        xhExtra.bindFormReset(_form);
        //返回
        xhExtra.bindFormBack();
        //列表添加按钮
        xhExtra.bindListAdd(_form);
        //保存按钮点击
        if(_btSave && _option.modifyUrl) {
            xhExtra.bindFormSave(_btSave, _option.modifyUrl, _form, _dataGrid);
        }
        //删除按钮
        if(_option.deleteUrl && _option.idField) {
           xhExtra.bindListDel(_dataGrid, _option.idField, _option.deleteUrl);
        }
    },
    bindFormSave: function(_btSave, _modifyUrl, _form, _dataGrid){
        _btSave.click(function () {
            _form.submit(baseUrl + _modifyUrl, {}, function (data) {
                if (xhExtra.checkError(data)) return false;
                xhExtra.backToList(_dataGrid);
            });
        });
    },
    clearLoadSuccess: function(_dataGrid){
        _dataGrid.onLoadSuccess = function(data){
            xhExtra.checkError(data);
            _dataGrid.clear();
        };
    },
    bindFormReset: function(_form){
        $('#bt_form_reset').click(function(){
            _form.reset();
        });
    },
    bindFormBack: function(){
        $('#bt_form_back').click(function(){
            xhExtra.backToList();
        });
    },
    bindListAdd: function(_form){
        $('#bt_list_add').click(function(){
            _form.reset();
            xhExtra.forwardToForm(false);
        });
    },
    bindListDel: function(_dataGrid, _idField, _deleteUrl){
        $('#bt_list_del').click(function () {
            if (xhExtra.buttonDisabled($(this))) return false;
            var ids = _dataGrid.getSelectValues(_idField);
            if (!ids) {
                window.top.xhTop.showMessage({type: 'error', title: '未选择数据！'});
                return false;
            }
            xhExtra.askChangeStatus(_deleteUrl, ids, _dataGrid);
        });
    },
    /**
     * 绑定顶层modal确认点击事件
     *
     * @param _callback
     *
     * create by ck 20170702
     */
    bindModalConfirm: function(_callback){
        $('#bt_modal_confirm', window.top.document).unbind('click').bind('click', function(){
            _callback.call(this);
        });
    },
    /**
     * 根据dom节点获取数据（easyui）
     *
     * @param _dom
     * @returns {*}
     *
     * create by ck 20170705
     */
    getValue: function(_dom){
        if(_dom.length <= 0) return '';
        var _tag_name = _dom[0].tagName;
        switch (_tag_name.toLowerCase()){
            case 'select': return _dom.combobox(_dom.combobox('options').multiple ? 'getValues' : 'getValue');
            case 'input' : return _dom.textbox('getText');
        }
    },
    setBtnLoading: function (_dom) {
        _dom.append(' <i class="fa fa-spinner fa-spin"></i>').attr('disabled', true);
    },
    setBtnNormal: function (_dom) {
        _dom.text(_dom.text()).attr('disabled', false);
    }
};